package utils;

import java.util.List;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.EuclideanDistanceSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.JDBCDataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class UserCF {

	final static int NEIGHBORHOOD_NUM = 3;   //用户邻居数量
	
	public static List<RecommendedItem> getCF(long uid,String type) {
		// TODO Auto-generated method stub

		
		//连接MySQL
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setServerName("localhost");
        dataSource.setUser("root");
        dataSource.setPassword("");
        dataSource.setDatabaseName("yac");
        
        JDBCDataModel dataModel = new MySQLJDBCDataModel(dataSource, "read_log", "uid", type, "pd","time");
        
        DataModel model = dataModel;
        
        //计算相似度
     
        NearestNUserNeighborhood neighbor;
		try {
			 //基于用户的协同过滤算法，基于物品的协同过滤算法
	        UserSimilarity user = new EuclideanDistanceSimilarity(model);  //计算欧式距离，欧式距离来定义相似性，用s=1/(1+d)来表示，范围在[0,1]之间，值越大，表明d越小，距离越近，则表示相似性越大
			neighbor = new NearestNUserNeighborhood(NEIGHBORHOOD_NUM, user, model);
			//构建基于用户的推荐系统
	        Recommender r = new GenericUserBasedRecommender(model, neighbor, user);
	        List<RecommendedItem> list = r.recommend(uid,5);  //获取推荐结果
            //遍历推荐结果
            System.out.print("|| 推荐：");
            for(RecommendedItem ritem : list)
            {
                System.out.print(ritem.getItemID()+" ");
            }
            System.out.println();
	        return list;
//	      //得到所有用户的id集合
//	        LongPrimitiveIterator iter = model.getUserIDs();
//
//	        while(iter.hasNext())
//	        {
//	            long uid = iter.nextLong();
//	            List<RecommendedItem> list = r.recommend(uid,3);  //获取推荐结果
//	            System.out.printf("用户:%s",uid);
//	            //遍历推荐结果
//	            System.out.print("|| 推荐文章：");
//	            for(RecommendedItem ritem : list)
//	            {
//	                System.out.print(ritem.getItemID()+" ");
//	            }
//	            System.out.println();
//	        }
		} catch (TasteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

        
	}

}
